<template>
  <lay-layer
    v-model="visible"
    :title="mode === 'add' ? '新增SKU' : '编辑SKU'"
    :area="['90%', '90%']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="sku-edit-dialog">
      <!-- 商品信息概览 -->
      <div class="product-overview" v-if="productData">
        <div class="product-info">
          <div class="product-image">
            <img 
              v-if="productData.images && productData.images.length > 0" 
              :src="productData.images[0]" 
              :alt="productData.name"
            />
            <div v-else class="no-image">暂无图片</div>
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ productData.name }}</h3>
            <p class="product-subtitle">{{ productData.subtitle }}</p>
            <div class="product-meta">
              <span class="meta-item">SPU: {{ productData.spuCode }}</span>
              <span class="meta-item">分类: {{ productData.category?.name }}</span>
              <span class="meta-item">品牌: {{ productData.brand?.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 表单内容 -->
      <div class="form-container">
        <lay-form :model="formData" ref="formRef" required>
          <!-- 基础信息卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h4>基础信息</h4>
            </div>
            <div class="card-content">
              <lay-row :space="16">
                <lay-col :md="8">
                  <lay-form-item label="SKU编码" prop="skuCode" required>
                    <lay-input 
                      v-model="formData.skuCode" 
                      placeholder="请输入SKU编码或点击生成"
                      style="width: calc(100% - 80px); margin-right: 8px;"
                    />
                    <lay-button @click="generateSkuCode" :loading="generatingCode">
                      生成
                    </lay-button>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="8">
                  <lay-form-item label="SKU名称">
                    <lay-input 
                      v-model="formData.name" 
                      placeholder="请输入SKU名称（可选）"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="8">
                  <lay-form-item label="状态">
                    <lay-select v-model="formData.status" placeholder="请选择状态">
                      <lay-select-option :value="1">启用</lay-select-option>
                      <lay-select-option :value="0">禁用</lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
              </lay-row>
            </div>
          </div>

          <!-- 规格属性卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h4>规格属性</h4>
              <lay-button size="sm" @click="addSpecification">
                <lay-icon type="layui-icon-add-1"></lay-icon>
                添加规格
              </lay-button>
            </div>
            <div class="card-content">
              <div class="specifications-container">
                <div 
                  v-for="(spec, index) in specifications" 
                  :key="index"
                  class="spec-item"
                >
                  <div class="spec-inputs">
                    <lay-input 
                      v-model="spec.name" 
                      placeholder="规格名称（如：颜色、尺寸）"
                      class="spec-name"
                    />
                    <lay-input 
                      v-model="spec.value" 
                      placeholder="规格值（如：红色、XL）"
                      class="spec-value"
                    />
                  </div>
                  <lay-button 
                    size="sm" 
                    type="danger" 
                    @click="removeSpecification(index)"
                    class="spec-remove"
                  >
                    <lay-icon type="layui-icon-delete"></lay-icon>
                  </lay-button>
                </div>
                <div v-if="specifications.length === 0" class="no-spec-tip">
                  <lay-icon type="layui-icon-tips"></lay-icon>
                  暂无规格属性，点击"添加规格"按钮添加
                </div>
              </div>
            </div>
          </div>

          <!-- 价格库存卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h4>价格与库存</h4>
            </div>
            <div class="card-content">
              <lay-row :space="16">
                <lay-col :md="6">
                  <lay-form-item label="销售价格" prop="price" required>
                    <lay-input-number 
                      v-model="formData.price" 
                      :min="0" 
                      :step="0.01"
                      :precision="2"
                      placeholder="请输入销售价格"
                      style="width: 100%;"
                    >
                      <template #prefix>¥</template>
                    </lay-input-number>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="6">
                  <lay-form-item label="原价">
                    <lay-input-number 
                      v-model="formData.originalPrice" 
                      :min="0" 
                      :step="0.01"
                      :precision="2"
                      placeholder="请输入原价"
                      style="width: 100%;"
                    >
                      <template #prefix>¥</template>
                    </lay-input-number>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="6">
                  <lay-form-item label="成本价">
                    <lay-input-number 
                      v-model="formData.costPrice" 
                      :min="0" 
                      :step="0.01"
                      :precision="2"
                      placeholder="请输入成本价"
                      style="width: 100%;"
                    >
                      <template #prefix>¥</template>
                    </lay-input-number>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="6">
                  <lay-form-item label="库存数量" prop="stockQuantity" required>
                    <lay-input-number 
                      v-model="formData.stockQuantity" 
                      :min="0"
                      placeholder="请输入库存数量"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="6">
                  <lay-form-item label="库存预警">
                    <lay-input-number 
                      v-model="formData.lowStockThreshold" 
                      :min="0"
                      placeholder="库存预警阈值"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="6">
                  <lay-form-item label="条形码">
                    <lay-input 
                      v-model="formData.barcode" 
                      placeholder="请输入条形码（可选）"
                    />
                  </lay-form-item>
                </lay-col>
              </lay-row>
            </div>
          </div>

          <!-- 物理属性卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h4>物理属性</h4>
            </div>
            <div class="card-content">
              <lay-row :space="16">
                <lay-col :md="8">
                  <lay-form-item label="重量(g)">
                    <lay-input-number 
                      v-model="formData.weight" 
                      :min="0"
                      :step="0.1"
                      placeholder="请输入重量"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="8">
                  <lay-form-item label="长度(cm)">
                    <lay-input-number 
                      v-model="formData.length" 
                      :min="0"
                      :step="0.1"
                      placeholder="请输入长度"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="8">
                  <lay-form-item label="宽度(cm)">
                    <lay-input-number 
                      v-model="formData.width" 
                      :min="0"
                      :step="0.1"
                      placeholder="请输入宽度"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
                <lay-col :md="8">
                  <lay-form-item label="高度(cm)">
                    <lay-input-number 
                      v-model="formData.height" 
                      :min="0"
                      :step="0.1"
                      placeholder="请输入高度"
                      style="width: 100%;"
                    />
                  </lay-form-item>
                </lay-col>
              </lay-row>
            </div>
          </div>

          <!-- SKU图片卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h4>SKU图片</h4>
              <div class="upload-tips">
                <span>建议尺寸：800x800像素，支持JPG、PNG、WEBP格式，单张不超过2MB</span>
              </div>
            </div>
            <div class="card-content">
              <div class="image-upload-container">
                <div class="image-list">
                  <div 
                    v-for="(image, index) in formData.images" 
                    :key="index"
                    class="image-item"
                  >
                    <img :src="image" :alt="`SKU图片${index + 1}`" />
                    <div class="image-overlay">
                      <div class="image-actions">
                        <lay-button 
                          size="xs" 
                          @click="previewImage(image)"
                          style="margin-bottom: 4px;"
                        >
                          <lay-icon type="layui-icon-search"></lay-icon>
                        </lay-button>
                        <lay-button 
                          size="xs" 
                          @click="moveImage(index, -1)" 
                          :disabled="index === 0"
                          style="margin-bottom: 4px;"
                        >
                          <lay-icon type="layui-icon-left"></lay-icon>
                        </lay-button>
                        <lay-button 
                          size="xs" 
                          @click="moveImage(index, 1)" 
                          :disabled="index === formData.images.length - 1"
                          style="margin-bottom: 4px;"
                        >
                          <lay-icon type="layui-icon-right"></lay-icon>
                        </lay-button>
                        <lay-button 
                          size="xs" 
                          type="danger" 
                          @click="removeImage(index)"
                        >
                          <lay-icon type="layui-icon-delete"></lay-icon>
                        </lay-button>
                      </div>
                    </div>
                    <div class="image-index">{{ index + 1 }}</div>
                  </div>
                  <div 
                    class="upload-item" 
                    @click="handleImageUpload"
                    v-if="formData.images.length < 5"
                  >
                    <lay-icon type="layui-icon-add-1" size="32"></lay-icon>
                    <div class="upload-text">上传图片</div>
                    <div class="upload-count">{{ formData.images.length }}/5</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </lay-form>
      </div>

      <!-- 底部操作栏 -->
      <div class="dialog-footer">
        <div class="footer-left">
          <lay-button @click="handleReset" v-if="mode === 'add'">
            <lay-icon type="layui-icon-refresh"></lay-icon>
            重置表单
          </lay-button>
        </div>
        <div class="footer-right">
          <lay-button @click="handleClose">取消</lay-button>
          <lay-button type="primary" @click="handleSubmit" :loading="loading">
            <lay-icon :type="mode === 'add' ? 'layui-icon-add-1' : 'layui-icon-edit'"></lay-icon>
            {{ mode === 'add' ? '创建SKU' : '更新SKU' }}
          </lay-button>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件上传 -->
    <input 
      ref="fileInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { layer } from '@layui/layui-vue'
import { productApi } from '../../../../api/module/product'
import { UploadApi } from '../../../../api/module/upload'

interface Props {
  visible: boolean
  skuData?: any
  productData?: any
  mode: 'add' | 'edit'
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const generatingCode = ref(false)
const formRef = ref()
const fileInput = ref()

// 表单数据
const formData = reactive({
  skuCode: '',
  name: '',
  specifications: {},
  price: 0,
  originalPrice: 0,
  costPrice: 0,
  stockQuantity: 0,
  lowStockThreshold: 10,
  weight: 0,
  length: 0,
  width: 0,
  height: 0,
  barcode: '',
  images: [] as string[],
  status: 1
})

// 规格数据
const specifications = ref<Array<{ name: string; value: string }>>([])

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听规格变化
watch(specifications, (newSpecs) => {
  const specs: Record<string, any> = {}
  newSpecs.forEach(spec => {
    if (spec.name && spec.value) {
      specs[spec.name] = spec.value
    }
  })
  formData.specifications = specs
}, { deep: true })

// 监听弹窗显示
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 初始化表单
const initForm = () => {
  if (props.mode === 'edit' && props.skuData) {
    Object.assign(formData, {
      ...props.skuData,
      images: props.skuData.images || []
    })
    
    // 处理规格
    if (formData.specifications) {
      specifications.value = Object.entries(formData.specifications).map(([name, value]) => ({
        name,
        value: String(value)
      }))
    }
  } else {
    // 重置表单
    resetForm()
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    skuCode: '',
    name: '',
    specifications: {},
    price: 0,
    originalPrice: 0,
    costPrice: 0,
    stockQuantity: 0,
    lowStockThreshold: 10,
    weight: 0,
    length: 0,
    width: 0,
    height: 0,
    barcode: '',
    images: [],
    status: 1
  })
  specifications.value = []
}

// 生成SKU编码
const generateSkuCode = async () => {
  try {
    generatingCode.value = true
    
    // 生成SKU编码规则：SPU前缀 + 规格简码 + 时间戳后4位 + 随机数
    const spuPrefix = props.productData?.spuCode?.slice(-4) || 'SKU'
    const specCode = generateSpecCode()
    const timestamp = Date.now().toString().slice(-4)
    const random = Math.floor(Math.random() * 100).toString().padStart(2, '0')
    
    const skuCode = `${spuPrefix}${specCode}${timestamp}${random}`
    formData.skuCode = skuCode
    
    layer.msg('SKU编码生成成功', { icon: 1 })
  } catch (error) {
    console.error('生成SKU编码失败:', error)
    layer.msg('生成SKU编码失败', { icon: 2 })
  } finally {
    generatingCode.value = false
  }
}

// 生成规格简码
const generateSpecCode = () => {
  if (specifications.value.length === 0) return ''
  
  return specifications.value
    .map(spec => spec.value.charAt(0).toUpperCase())
    .join('')
    .slice(0, 3)
}

// 添加规格
const addSpecification = () => {
  specifications.value.push({ name: '', value: '' })
}

// 删除规格
const removeSpecification = (index: number) => {
  specifications.value.splice(index, 1)
}

// 图片上传
const handleImageUpload = () => {
  if (formData.images.length >= 5) {
    layer.msg('最多只能上传5张图片', { icon: 3 })
    return
  }
  fileInput.value?.click()
}

// 文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (!files || files.length === 0) return

  const remainingSlots = 5 - formData.images.length
  const filesToUpload = Array.from(files).slice(0, remainingSlots)

  for (const file of filesToUpload) {
    // 验证文件
    if (!file.type.startsWith('image/')) {
      layer.msg('只能上传图片文件', { icon: 3 })
      continue
    }
    if (file.size > 2 * 1024 * 1024) {
      layer.msg('图片大小不能超过2MB', { icon: 3 })
      continue
    }

    try {
      const uploadFormData = new FormData()
      uploadFormData.append('file', file)
      const response = await UploadApi.uploadImage(uploadFormData)
      if (response.data.code === 200) {
        formData.images.push(response.data.data.url)
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      layer.msg('图片上传失败', { icon: 2 })
    }
  }

  // 清空文件输入
  target.value = ''
}

// 预览图片
const previewImage = (imageUrl: string) => {
  layer.photos({
    photos: {
      data: [{ src: imageUrl }]
    }
  })
}

// 移动图片
const moveImage = (index: number, direction: number) => {
  const newIndex = index + direction
  if (newIndex < 0 || newIndex >= formData.images.length) return

  const images = [...formData.images]
  const temp = images[index]
  images[index] = images[newIndex]
  images[newIndex] = temp
  formData.images = images
}

// 删除图片
const removeImage = (index: number) => {
  formData.images.splice(index, 1)
}

// 重置表单
const handleReset = () => {
  layer.confirm('确定要重置表单吗？所有已填写的内容将被清空。', {
    title: '确认重置',
    icon: 3
  }, () => {
    resetForm()
    layer.msg('表单已重置', { icon: 1 })
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value?.validate()
    if (!valid) return

    if (!props.productData?.id) {
      layer.msg('商品信息不完整', { icon: 3 })
      return
    }

    loading.value = true

    const submitData = { ...formData }
    
    if (props.mode === 'add') {
      await productApi.createProductSku(props.productData.id, submitData)
      layer.msg('创建成功', { icon: 1 })
    } else {
      await productApi.updateProductSku(props.productData.id, props.skuData.id, submitData)
      layer.msg('更新成功', { icon: 1 })
    }

    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    layer.msg('提交失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.sku-edit-dialog {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

/* 商品概览区域 */
.product-overview {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 16px;
  border: 1px solid #e0e0e0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
  font-size: 12px;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.product-subtitle {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.product-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  font-size: 12px;
  color: #999;
}

/* 表单容器 */
.form-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
}

/* 表单卡片 */
.form-card {
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
}

.card-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.card-content {
  padding: 20px;
}

/* 规格容器 */
.specifications-container {
  width: 100%;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.spec-inputs {
  display: flex;
  flex: 1;
  gap: 12px;
}

.spec-name {
  flex: 1;
}

.spec-value {
  flex: 1;
}

.spec-remove {
  margin-left: 12px;
}

.no-spec-tip {
  text-align: center;
  padding: 40px;
  color: #999;
  background: #f8f9fa;
  border-radius: 6px;
  border: 2px dashed #e0e0e0;
}

/* 图片上传 */
.image-upload-container {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.image-index {
  position: absolute;
  top: 4px;
  left: 4px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.upload-item {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-item:hover {
  border-color: #1890ff;
  color: #1890ff;
  background: #f0f8ff;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
}

.upload-count {
  margin-top: 4px;
  font-size: 12px;
  color: #666;
}

.upload-tips {
  font-size: 12px;
  color: #666;
}

/* 底部操作栏 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-top: 1px solid #e8e8e8;
  border-radius: 0 0 8px 8px;
  margin-top: auto;
}

.footer-left {
  flex: 1;
}

.footer-right {
  display: flex;
  gap: 8px;
}

/* 滚动条样式 */
.form-container::-webkit-scrollbar {
  width: 6px;
}

.form-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>